import { Controller, Inject, Get, Post, Body } from '@midwayjs/core'
import { MaterialService } from '../../service/admin/MaterialService'
import { BaseController } from '../base.chontroller'

@Controller('/material')
export class MaterialController extends BaseController {
  @Inject()
  service!: MaterialService

  @Get('/list')
  async list() {
    try {
      const data = await this.service.list()
      return this.success<IList<any>>(data)
    } catch (err: any) {
      return this.fail(err.message || '获取列表失败')
    }
  }

  // 获取所有物资选项（用于下拉框等场景）
  @Get('/options')
  async options() {
    try {
      const data = await this.service.getOptions()
      return this.success(data, '获取物资选项成功')
    } catch (err: any) {
      return this.fail(err.message || '获取物资选项失败')
    }
  }

  @Post('/add')
  async add(@Body() data: any) {
    if (!data?.name || !data?.price) {
      return this.fail('缺少必要参数')
    }
    try {
      const result = await this.service.add(data)
      return this.success(result, '添加成功')
    } catch (err: any) {
      return this.fail(err.message || '添加失败')
    }
  }

  @Post('/edit')
  async edit(@Body() data: any) {
    if (!data?.id) {
      return this.fail('缺少ID参数')
    }
    try {
      const result = await this.service.edit(data)
      return this.success(result, '编辑成功')
    } catch (err: any) {
      return this.fail(err.message || '编辑失败')
    }
  }

  @Post('/delete')
  async delete(@Body() data: any) {
    if (!data?.id) {
      return this.fail('缺少ID参数')
    }
    try {
      await this.service.delete(data.id)
      return this.success(null, '删除成功')
    } catch (err: any) {
      return this.fail(err.message || '删除失败')
    }
  }
}
